import os

from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from rest_framework.decorators import action
from rest_framework.viewsets import GenericViewSet, mixins

from common.page import page_
from mainapp.serializers import *
from common.error import *


class UserApiView(GenericViewSet):
    queryset = TUser.objects.all()
    serializer_class = TUserSerializer

    # 注册
    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def register(self, request):
        ser = self.get_serializer(data=request.data)  # 接收请求参数并将其封装到序列化对象（CheckRegUserSerializer）中
        try:
            ser.is_valid()
        except NewsException as e:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': e.detail
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        username = ser.data.get("email", '')
        password = ser.data.get("password", '')
        user = TUser.objects.filter(username=username)
        if user:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '该账号已注册'
            }
        else:
            new_user = TUser.objects.create_user(username=username, password=password)
            login(request, new_user)
            info = {
                'successful': True,
                'data': new_user.username,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '注册成功，已登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 登录
    @action(methods=['POST'], detail=False)
    def login_(self, request):
        email = request.data.get('email', '')
        password = request.data.get('password', '')
        # vaild = request.data.get('valid', '')
        user = authenticate(username=email, password=password)
        if user:
            login(request, user)
            info = {
                'successful': True,
                'data': user.username,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '登录成功'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '账户或密码错误'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 退出
    @action(methods=['GET'], detail=False)
    def logout_(self, request):
        logout(request)
        info = {
            'successful': True,
            'data': None,
            'code': ERROR_CODE_OPERATION_SUCCESS,
            'message': '退出成功'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


class ProjectApiView(GenericViewSet, mixins.CreateModelMixin, mixins.ListModelMixin):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

    def create(self, request, *args, **kwargs):
        pass
